import 'package:flutter/material.dart';
import 'constants/app_constants.dart';
import 'constants/app_dimensions.dart';
import 'services/ollama_service.dart';
import 'widgets/chat_bubble.dart';
import 'models/chat_message.dart';
import 'services/speech_to_text_service.dart';
import 'widgets/documentation_viewer.dart';
import 'screens/auth_screen.dart';
import 'services/platform_service.dart';

class PromptTemplates {
  static const search = '''我现在需要搜索一些信息，请你帮我提供准确、全面的搜索结果。
请记住以下几点：
1. 给出的信息要准确可靠
2. 尽可能提供最新的相关信息
3. 如果有多个来源，请列出参考来源
4. 如果信息可能不准确，请明确指出

请告诉我你想搜索什么？''';

  static const qa = '''我是你的智能助手，可以回答你的各种问题。
我会：
1. 给出清晰、准确的解答
2. 使用易于理解的语言
3. 如果问题涉及多个方面，会分点说明
4. 在必要时提供例子

请问你想了解什么？''';

  static const writing = '''我是你的写作助手，可以帮你：
1. 创作各类文章
2. 改进文字表达
3. 优化文章结构
4. 提供写作建议

请告诉我你需要什么样的写作帮助？''';
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // 添加作者信息
  static const author = '通信小李哥';
  static const email = '3263394665@qq.com';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AI Assistant',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
        platform: _getPlatformTarget(),
        pageTransitionsTheme: PageTransitionsTheme(
          builders: {
            TargetPlatform.android: const CupertinoPageTransitionsBuilder(),
            TargetPlatform.iOS: const CupertinoPageTransitionsBuilder(),
            TargetPlatform.fuchsia: const FadeUpwardsPageTransitionsBuilder(),
          },
        ),
      ),
      home: const AuthScreen(),
    );
  }

  TargetPlatform _getPlatformTarget() {
    if (PlatformService.isIOS) return TargetPlatform.iOS;
    if (PlatformService.isAndroid) return TargetPlatform.android;
    return TargetPlatform.fuchsia;
  }
}

class ChatScreen extends StatefulWidget {
  const ChatScreen({super.key});

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen>
    with SingleTickerProviderStateMixin {
  final TextEditingController _controller = TextEditingController();
  final List<ChatMessage> _messages = [];
  final OllamaService _ollamaService = OllamaService();
  final bool _isLoading = false;
  List<String> _availableModels = [];
  String _selectedModel = 'llama2';

  // 添加动画控制器
  late AnimationController _drawerController;
  late Animation<double> _drawerAnimation;
  bool _isDrawerOpen = false;

  // 添加语音输入服务
  final SpeechToTextService _speechToTextService = SpeechToTextService();
  bool _isListening = false;

  @override
  void initState() {
    super.initState();
    _loadModels();

    // 初始化抽屉动画
    _drawerController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 250),
    );

    _drawerAnimation = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(CurvedAnimation(
      parent: _drawerController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _drawerController.dispose();
    super.dispose();
  }

  void _toggleDrawer() {
    setState(() {
      _isDrawerOpen = !_isDrawerOpen;
      if (_isDrawerOpen) {
        _drawerController.forward();
      } else {
        _drawerController.reverse();
      }
    });
  }

  Future<void> _loadModels() async {
    final models = await _ollamaService.getAvailableModels();
    setState(() {
      _availableModels = models;
      if (models.isNotEmpty) {
        _selectedModel = models.first;
        _ollamaService.setModel(_selectedModel);
      }
    });
  }

  Widget _buildChatBody() {
    if (_messages.isEmpty) {
      return SingleChildScrollView(
        child: SafeArea(
          child: Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(height: 20),
                // Logo
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.psychology,
                    size: 48,
                    color: AppColors.primary,
                  ),
                ),
                const SizedBox(height: 16),
                // 标题和副标题
                Text(
                  AppText.translations['welcomeTitle']!,
                  style: const TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                Text(
                  AppText.translations['welcomeSubtitle']!,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 24),
                // 功能卡片
                ...AppText.features.entries.map((feature) => Padding(
                      padding: const EdgeInsets.only(bottom: 12),
                      child: _buildFeatureCard(
                        icon: _getFeatureIcon(feature.key),
                        title: feature.value['title']!,
                        description: feature.value['description']!,
                      ),
                    )),
                const SizedBox(height: 16),
                // 当前模型信息
                _buildModelInfo(),
              ],
            ),
          ),
        ),
      );
    } else {
      return Column(
        children: [
          Expanded(
            child: RefreshIndicator(
              onRefresh: _refreshChat,
              child: ListView.builder(
                itemCount: _messages.length,
                reverse: true,
                itemBuilder: (context, index) {
                  final message = _messages[_messages.length - 1 - index];
                  return ChatBubble(message: message);
                },
              ),
            ),
          ),
          if (_isLoading)
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: CircularProgressIndicator(),
            ),
          _buildInputArea(),
        ],
      );
    }
  }

  Widget _buildFeatureCard({
    required IconData icon,
    required String title,
    required String description,
  }) {
    return InkWell(
      onTap: () => _handleFeatureCardTap(title),
      borderRadius: BorderRadius.circular(12),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.withOpacity(0.2)),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Icon(icon, size: 32, color: Colors.blue),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    description,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            const Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  void _handleFeatureCardTap(String title) {
    String prompt;
    switch (title) {
      case '智能搜索':
        prompt = PromptTemplates.search;
        break;
      case '解答疑惑':
        prompt = PromptTemplates.qa;
        break;
      case '创意写作':
        prompt = PromptTemplates.writing;
        break;
      default:
        return;
    }

    setState(() {
      _messages.add(ChatMessage(
        id: DateTime.now().toString(),
        text: prompt,
        isUser: false,
        status: MessageStatus.sent,
      ));
    });

    FocusScope.of(context).requestFocus(FocusNode());
    _controller.clear();
  }

  Widget _buildBottomButtons() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 底部按钮栏
        Container(
          padding: const EdgeInsets.symmetric(vertical: 8),
          decoration: BoxDecoration(
            border: Border(
              top: BorderSide(
                color: Colors.grey.withOpacity(0.2),
              ),
            ),
          ),
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // 删除底部按钮
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildInputArea() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: EdgeInsets.only(
            left: 16,
            right: 16,
            top: 8,
            bottom: PlatformService.isIOS
                ? MediaQuery.of(context).padding.bottom + 8
                : 8,
          ),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(24),
            ),
            child: Row(
              children: [
                // Only show voice button on mobile platforms
                if (PlatformService.supportsVoiceInput) _buildVoiceButton(),
                Expanded(
                  child: TextField(
                    controller: _controller,
                    enabled: !_isLoading,
                    maxLines: null,
                    keyboardType: TextInputType.multiline,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (value) {
                      if (value.isNotEmpty && !_isLoading) {
                        _sendMessage();
                      }
                    },
                    decoration: InputDecoration(
                      hintText: _isLoading ? '正在生成回复...' : '给 DeepSeek 发送消息',
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 8,
                      ),
                    ),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: _isLoading
                      ? null
                      : () {
                          if (_controller.text.isNotEmpty) {
                            _sendMessage();
                          }
                        },
                  color: _controller.text.isEmpty || _isLoading
                      ? Colors.grey
                      : Colors.blue,
                ),
              ],
            ),
          ),
        ),
        _buildBottomButtons(),
      ],
    );
  }

  // 修改语音按钮组件
  Widget _buildVoiceButton() {
    return GestureDetector(
      onTap: () {
        _showVoiceDialog(); // 点击显示对话框
      },
      child: Container(
        padding: const EdgeInsets.all(8.0),
        child: const Icon(
          Icons.mic_none,
          color: Colors.grey,
        ),
      ),
    );
  }

  // 修改语音对话框
  void _showVoiceDialog() {
    showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (dialogContext) => Center(
        child: GestureDetector(
          onTapDown: (_) async {
            final hasPermission = await _speechToTextService.initialize();
            if (hasPermission) {
              setState(() => _isListening = true);
              try {
                await _speechToTextService.startListening((text) {
                  setState(() {
                    _controller.text = text;
                  });
                });
              } catch (e) {
                // 处理录音错误
                setState(() => _isListening = false);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text('语音识别失败: ${e.toString()}'),
                    backgroundColor: Colors.red,
                  ),
                );
                Navigator.of(dialogContext).pop();
              }
            } else {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('需要麦克风权限才能使用语音输入')),
              );
              Navigator.of(dialogContext).pop();
            }
          },
          onTapUp: (_) async {
            if (_isListening) {
              await _speechToTextService.stopListening();
              if (mounted) {
                setState(() => _isListening = false);
                Navigator.of(dialogContext).pop();
                if (_controller.text.isNotEmpty) {
                  _sendMessage();
                }
              }
            }
          },
          onTapCancel: () async {
            if (_isListening) {
              await _speechToTextService.stopListening();
              if (mounted) {
                setState(() => _isListening = false);
                Navigator.of(dialogContext).pop();
              }
            }
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            width: _isListening ? 180 : 160,
            height: _isListening ? 180 : 160,
            decoration: BoxDecoration(
              color: Colors.black.withAlpha((0.3 * 255).toInt()),
              borderRadius: BorderRadius.circular(20),
              border: _isListening
                  ? Border.all(color: Colors.blue, width: 2)
                  : null,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                AnimatedContainer(
                  duration: const Duration(milliseconds: 200),
                  height: _isListening ? 60 : 48,
                  width: _isListening ? 60 : 48,
                  child: Icon(
                    _isListening ? Icons.mic : Icons.mic_none,
                    color: _isListening ? Colors.red : Colors.white,
                    size: _isListening ? 36 : 48,
                  ),
                ),
                const SizedBox(height: 16),
                Text(
                  _isListening ? '正在聆听...' : '按住说话',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                  ),
                ),
                if (_isListening)
                  Padding(
                    padding: const EdgeInsets.only(top: 16),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 4,
                          height: 20,
                          margin: const EdgeInsets.symmetric(horizontal: 2),
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(2),
                          ),
                          child: _buildPulseAnimation(),
                        ),
                        Container(
                          width: 4,
                          height: 20,
                          margin: const EdgeInsets.symmetric(horizontal: 2),
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(2),
                          ),
                          child: _buildPulseAnimation(delay: 0.2),
                        ),
                        Container(
                          width: 4,
                          height: 20,
                          margin: const EdgeInsets.symmetric(horizontal: 2),
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(2),
                          ),
                          child: _buildPulseAnimation(delay: 0.4),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPulseAnimation({double delay = 0.0}) {
    return Container(
      width: 4,
      height: 20,
      decoration: BoxDecoration(
        color: Colors.blue,
        borderRadius: BorderRadius.circular(2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: !_isDrawerOpen,
      onPopInvoked: (didPop) {
        if (_isDrawerOpen) {
          _toggleDrawer();
        }
      },
      child: Scaffold(
        appBar: _buildAppBar(),
        body: Stack(
          children: [
            _buildChatBody(),
            if (_isDrawerOpen)
              GestureDetector(
                onTap: _toggleDrawer,
                child: Container(
                  color: Colors.black.withOpacity(0.3 * _drawerAnimation.value),
                ),
              ),
            _buildDrawer(),
          ],
        ),
      ),
    );
  }

  AppBar _buildAppBar() {
    return AppBar(
      leading: IconButton(
        icon: const Icon(Icons.history),
        onPressed: _showHistoryDialog,
      ),
      title: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(_selectedModel),
          const SizedBox(width: 8),
          const Icon(Icons.api, size: AppDimensions.iconSize),
        ],
      ),
      centerTitle: true,
      actions: [
        IconButton(
          icon: const Icon(Icons.menu_book),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute<void>(
                builder: (context) => const DocumentationViewer(),
              ),
            );
          },
          tooltip: '查看文档',
        ),
        IconButton(
          icon: const Icon(Icons.model_training),
          onPressed: _showModelSelector,
          tooltip: '选择模型',
        ),
      ],
    );
  }

  Widget _buildDrawer() {
    return AnimatedBuilder(
      animation: _drawerAnimation,
      builder: (context, child) {
        return Transform.translate(
          offset: Offset(
              -AppDimensions.drawerWidth * (1 - _drawerAnimation.value), 0),
          child: Material(
            elevation: 16,
            child: Container(
              width: AppDimensions.drawerWidth,
              margin: EdgeInsets.only(top: -MediaQuery.of(context).padding.top),
              height: MediaQuery.of(context).size.height +
                  MediaQuery.of(context).padding.top,
              color: Colors.white,
              child: Column(
                children: [
                  AppBar(
                    backgroundColor: Theme.of(context).primaryColor,
                    leading: IconButton(
                      icon: const Icon(Icons.close, color: Colors.white),
                      onPressed: _toggleDrawer,
                    ),
                    title: Text(
                      AppText.translations['historyTitle']!,
                      style: const TextStyle(color: Colors.white),
                    ),
                    actions: [
                      IconButton(
                        icon: const Icon(
                          Icons.delete_outline,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          showDialog<void>(
                            context: context,
                            builder: (context) => AlertDialog(
                              title: const Text('清空历史记录'),
                              content: const Text('确定要清空所有聊天记录吗？此操作不可恢复。'),
                              actions: [
                                TextButton(
                                  onPressed: () => Navigator.pop(context),
                                  child: const Text('取消'),
                                ),
                                TextButton(
                                  onPressed: () {
                                    setState(() {
                                      _messages.clear();
                                    });
                                    Navigator.pop(context);
                                    _toggleDrawer();
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text('历史记录已清空'),
                                        duration: Duration(seconds: 2),
                                      ),
                                    );
                                  },
                                  child: const Text(
                                    '确定',
                                    style: TextStyle(color: Colors.red),
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                        tooltip: '清空历史记录',
                      ),
                    ],
                  ),
                  Expanded(
                    child: ListView.builder(
                      itemCount: _messages.length,
                      reverse: false,
                      itemBuilder: (context, index) {
                        final message = _messages[index];
                        return ListTile(
                          title: Text(
                            message.text,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          leading: Icon(
                            message.isUser ? Icons.person : Icons.android,
                            color: message.isUser
                                ? AppColors.primary
                                : Colors.green,
                          ),
                          onTap: () {
                            _toggleDrawer();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  void _sendMessage() async {
    if (_controller.text.isEmpty) return;

    final userMessage = _controller.text;
    _controller.clear();

    // 添加用户消息
    final userChatMessage = ChatMessage(
      id: DateTime.now().toString(),
      text: userMessage,
      isUser: true,
      status: MessageStatus.sent,
    );

    // 添加AI消息（初始为空）
    final aiMessage = ChatMessage(
      id: DateTime.now().toString(),
      text: '正在思考...', // 使用文字提示代替加载动画
      isUser: false,
      status: MessageStatus.sending,
    );

    setState(() {
      _messages.add(userChatMessage);
      _messages.add(aiMessage);
    });

    try {
      String fullPrompt = userMessage;
      if (_messages.length > 2) {
        final recentMessages = _messages.reversed.take(3).toList().reversed;
        final context = recentMessages
            .map((msg) => '${msg.isUser ? "用户" : "AI"}: ${msg.text}')
            .join('\n');
        fullPrompt = '$context\n用户: $userMessage';
      }

      String currentThinking = '';
      String currentAnswer = '';
      bool isThinking = false;

      await for (final chunk
          in _ollamaService.generateStreamResponse(fullPrompt)) {
        setState(() {
          if (chunk.contains('<think>')) {
            isThinking = true;
            currentThinking = '';
          } else if (chunk.contains('</think>')) {
            isThinking = false;
            aiMessage.text = '思考过程：\n$currentThinking\n\n回答：\n';
          } else {
            if (isThinking) {
              currentThinking += chunk;
              aiMessage.text = '思考过程：\n$currentThinking';
            } else {
              currentAnswer += chunk;
              aiMessage.text = currentThinking.isEmpty
                  ? currentAnswer
                  : '思考过程：\n$currentThinking\n\n回答：\n$currentAnswer';
            }
          }
        });
      }

      setState(() {
        aiMessage.status = MessageStatus.sent;
      });
    } catch (e) {
      setState(() {
        aiMessage.text = "抱歉，发生错误：$e";
        aiMessage.status = MessageStatus.error;
      });
    }
  }

  void _showModelSelector() {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.model_training),
            SizedBox(width: 8),
            Text('选择模型'),
          ],
        ),
        content: SizedBox(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (_availableModels.isEmpty)
                const Center(
                  child: Column(
                    children: [
                      Icon(Icons.warning, color: Colors.orange),
                      SizedBox(height: 8),
                      Text('没有可用的模型'),
                    ],
                  ),
                )
              else
                Flexible(
                  child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: _availableModels.length,
                    itemBuilder: (context, index) {
                      final model = _availableModels[index];
                      return RadioListTile<String>(
                        title: Text(model),
                        subtitle: const Text('点击选择使用此模型'),
                        value: model,
                        groupValue: _selectedModel,
                        onChanged: (value) {
                          setState(() {
                            _selectedModel = value!;
                            _ollamaService.setModel(_selectedModel);
                          });
                          Navigator.pop(context);
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text('已切换到模型: $value'),
                              duration: const Duration(seconds: 2),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  Future<void> _refreshChat() async {
    try {
      await _loadModels();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已刷新'),
            duration: Duration(seconds: 1),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('刷新失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  void _showHistoryDialog() {
    showDialog<void>(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: MediaQuery.of(context).size.width * 0.9,
          height: MediaQuery.of(context).size.height * 0.8,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: [
              // 标题栏
              Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor,
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(12),
                    topRight: Radius.circular(12),
                  ),
                ),
                child: Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8.0, vertical: 12),
                  child: Row(
                    children: [
                      IconButton(
                        icon: const Icon(Icons.close, color: Colors.white),
                        onPressed: () => Navigator.pop(context),
                      ),
                      const Text(
                        '历史记录',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const Spacer(),
                      IconButton(
                        icon: const Icon(
                          Icons.delete_outline,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          showDialog<void>(
                            context: context,
                            builder: (context) => AlertDialog(
                              title: const Text('清空历史记录'),
                              content: const Text('确定要清空所有聊天记录吗？此操作不可恢复。'),
                              actions: [
                                TextButton(
                                  onPressed: () => Navigator.pop(context),
                                  child: const Text('取消'),
                                ),
                                TextButton(
                                  onPressed: () {
                                    setState(() {
                                      _messages.clear();
                                    });
                                    Navigator.pop(context); // 关闭确认对话框
                                    Navigator.pop(context); // 关闭历史记录对话框
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text('历史记录已清空'),
                                        duration: Duration(seconds: 2),
                                      ),
                                    );
                                  },
                                  child: const Text(
                                    '确定',
                                    style: TextStyle(color: Colors.red),
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                        tooltip: '清空历史记录',
                      ),
                    ],
                  ),
                ),
              ),
              // 聊天记录列表
              Expanded(
                child: ListView.builder(
                  itemCount: _messages.length,
                  reverse: false,
                  padding: const EdgeInsets.all(8.0),
                  itemBuilder: (context, index) {
                    final message = _messages[index];
                    return Card(
                      elevation: 0,
                      color: message.isUser
                          ? Colors.blue.withOpacity(0.1)
                          : Colors.grey.withOpacity(0.1),
                      margin: const EdgeInsets.symmetric(vertical: 4.0),
                      child: ListTile(
                        title: Text(
                          message.text,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        leading: Icon(
                          message.isUser ? Icons.person : Icons.android,
                          color:
                              message.isUser ? AppColors.primary : Colors.green,
                        ),
                        onTap: () {
                          Navigator.pop(context);
                        },
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  IconData _getFeatureIcon(String featureKey) {
    switch (featureKey) {
      case 'search':
        return Icons.search;
      case 'qa':
        return Icons.question_answer;
      case 'writing':
        return Icons.edit_note;
      default:
        return Icons.star;
    }
  }

  Widget _buildModelInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.model_training, color: AppColors.primary),
              const SizedBox(width: 8),
              Text(
                '当前使用模型: $_selectedModel',
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          if (_availableModels.isNotEmpty) ...[
            const SizedBox(height: 8),
            Text(
              '可用模型: ${_availableModels.join(", ")}',
              style: const TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ],
      ),
    );
  }
}
